﻿using System;
using System.Reflection;
using EnvDTE;
using EnvDTE80;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.VisualStudio.Shell.Interop;
using ITrackSelection=Microsoft.SqlServer.Management.UI.VSIntegration.ITrackSelection;

namespace Skim.Ssms.AddIn.ActiveFileExplorer
{
    public static class ActiveFilesController
    {
        public static ActiveFilesWindow ActiveFilesWindow { get; private set; }

        public static void CreateAddInWindow(EnvDTE.AddIn addInInstance)
        {
            ActiveFilesWindow = CreateToolWindow(addInInstance).Object as ActiveFilesWindow;
            if (ActiveFilesWindow == null) return;
            
            ActiveFilesWindow.TrackSelection = 
                (ITrackSelection)ServiceCache.ServiceProvider.GetService(typeof(STrackSelection));
        }

        private static Window CreateToolWindow(EnvDTE.AddIn addinInstance)
        {
            var win2 = ServiceCache.ExtensibilityModel.Windows as Windows2;
            if (win2 == null) return null;

            object controlObject = null;
            var guidPosition = string.Format("{{{0}}}", new Guid(ToolWindowSettings.Default.Guid));

            var toolWindow = win2.CreateToolWindow2(addinInstance, Assembly.GetExecutingAssembly().Location, 
                ToolWindowSettings.Default.TypeName, ToolWindowSettings.Default.Caption, guidPosition, 
                ref controlObject);
            toolWindow.Visible = true;
            return toolWindow;
        }
    }
}